package org.jeecg.common.sdk.ocr;

import cn.hutool.core.codec.Base64Encoder;
import com.alibaba.fastjson.JSON;
import org.jeecg.common.rc.exception.JlException;
import lombok.SneakyThrows;
import okhttp3.*;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author zjarlin
 * @since 2023/11/20 11:49
 */
public class BaiduOcr {

    public static final String API_KEY = "ZhVbxrG0SF6BuXgevSeGbzC7";
    public static final String SECRET_KEY = "16cgiqjoYTcYh9QV1SGfvb3GFpgimpLd";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    @SneakyThrows
//    @Retryable(value = JlException.class)
   @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
    public static String getOcrString(MultipartFile file) {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String base64 = multipartFileToBase64(file);
        base64 = URLEncoder.encode(base64, "UTF-8");

        RequestBody body = RequestBody.create(mediaType, "image=" + base64 + "&detect_direction=false&paragraph=false&probability=false");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new JlException("ocr识别出错");

        }
        String string = response.body().string();
        return string;

    }

    public static String multipartFileToBase64(MultipartFile file) {
        try {
            // 读取 MultipartFile 的内容
            byte[] content = file.getBytes();

            // 将内容转换为 Base64 字符串
            String base64Str = Base64Encoder.encode(content);

            return base64Str;
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    @SneakyThrows
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                                                         + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String string = response.body().string();
        String o = JSON.parseObject(string).getString("access_token");
        return o;
    }
}
